<template>
  <m-window-frame
    :title="$t('FMU文件导入选项')"
    style="height: 100%"
    :okLoading="saveLoading"
    class="v-fmu-option"
    @cancel="handleCancel"
    @ok="handleSave"
  >
    <attr-tips :type="'fmuOption'"></attr-tips>
    <div class="fmu_content">
      <div class="fmu_top">
        <span class="block_name">
          {{ $t("模块名称") }}:
          <el-input
            v-model="currentName"
            :class="{ requiredInput: !currentName.length }"
          />
        </span>
        <span
          class="select_btn"
          @click="handleSelectAll"
        >
          <img
            src="statics/icons/app/icon_SelectAll.svg"
            class="g-pointer"
          />
          {{ $t("全选") }}
        </span>
        <span
          class="select_btn"
          @click="handleCancelSelectAll"
        >
          <img
            src="statics/icons/app/icon_CancelSelectAll.svg"
            class="g-pointer"
          />
          {{ $t("取消全选") }}
        </span>
      </div>
      <div class="fmu_banner">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          height="98%"
        >
          <el-table-column
            type="index"
            label="#"
            :index="(index: number) => index + 1"
          />
          <el-table-column
            prop="isCheck"
            width="50"
          >
            <template #default="{ row }">
              <el-checkbox
                v-model="row.isCheck"
                :disabled="row.disabled"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="direction"
            :label="$t('方向')"
          />
          <el-table-column
            prop="name"
            :label="$t('名称')"
          />
          <el-table-column :label="$t('类型')">
            <template #default="{ row }">
              <img
                v-if="TypeToIconKey[row['type']]"
                :src="TypeToIconKey[row['type']]"
              />
              {{ row["type"] }}
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            :label="$t('描述')"
          />
          <el-table-column :label="$t('作为端口')">
            <template #default="{ row }">
              <MDropdown
                :disabled="row.disabled"
                :class="{ disabled: row.disabled }"
                style="border: 1px solid #e4e3e3; height: 30px; line-height: 30px; width: 100%; cursor: pointer"
              >
                <div class="g-jc-sb g-pd-lr-8">
                  <div class="g-flex-1">{{ portSelectList.find(one => one.value === row.asPort)?.label || "None" }}</div>
                  <div class="g-flex-0">
                    <img
                      src="statics/icons/app/iconlist2.png"
                      class="g-pointer"
                    />
                  </div>
                </div>
                <template #dropdown>
                  <MDropdownMenuItem
                    v-for="(item, index) in portSelectList"
                    :key="index"
                    @click="handleAsPortOption(row, item.value)"
                  >
                    <span class="g-pd-lr-8">{{ item.label }}</span>
                  </MDropdownMenuItem>
                </template>
              </MDropdown>
            </template>
          </el-table-column>
          <el-table-column :label="$t('接口模块')">
            <template #default="{ row }">
              <MDropdown
                :disabled="row.disabled || row.asPort !== 2"
                :class="{ disabled: row.disabled || row.asPort !== 2 }"
                style="border: 1px solid #e4e3e3; height: 30px; line-height: 30px; width: 100%; cursor: pointer"
              >
                <div class="g-jc-sb g-pd-lr-8">
                  <img
                    v-if="row.interfaceBlock?.icon"
                    :src="row.interfaceBlock.icon"
                    class="g-pointer"
                  />
                  <div class="g-flex-1">{{ row.interfaceBlock?.name || "None" }}</div>
                  <div class="g-flex-0">
                    <img
                      src="statics/icons/app/iconlist2.png"
                      class="g-pointer"
                    />
                  </div>
                </div>
                <template #dropdown>
                  <ModelDropdown
                    :getList="() => blockSelectList"
                    @changeOption="(val: SelectOption) => changeOption(row, val)"
                  ></ModelDropdown>
                </template>
              </MDropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="fmu_footer">
        <el-checkbox
          v-model="attachFile"
          :disabled="allData?.disAbaleAttachFile"
        >
          {{ $t("将文件作为项目附件") }}
        </el-checkbox>
      </div>
    </div>
  </m-window-frame>
</template>
<script lang="ts" setup>
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import { WindowName } from "@/mdesign-lib/mdesign-main.js";
import { ref, watch, onMounted } from "vue";
import { localFile } from "@/localFile/LocalFile";
import { ipcWindowUtil } from "@/common/ipcWindow/IpcWindowUtil";
import { CloseData, FMUOptionParams } from "./index";
import { useRoute } from "vue-router";
import AttrTips from "@/common/attrTip/AttrTip.vue";
import ModelDropdown from "./ModelDropdown.vue";
import { SelectOption } from "../relationCriteria/types";
import { FmuResolutionOptionData, FmuResolutionOptionItem } from "@/constants/types";
import MDropdown from "@/common/dropdown/Dropdown.vue";
import MDropdownMenuItem from "@/common/dropdown/DropdownMenuItem.vue";
import { projectService, modelService } from "../../service";
import { loading } from "@/common/Loading";
const allData = ref<FmuResolutionOptionData>();
const route = useRoute();
const routeQuery = route.query as unknown;
let query = routeQuery as FMUOptionParams;
const saveLoading = ref(false);
watch(
  () => route.fullPath,
  async () => {
    const newRouteQuery = route.query as any;
    query = newRouteQuery;
    allData.value = JSON.parse(query.data) as FmuResolutionOptionData;
  },
  { immediate: true }
);
const TypeToIconKey = {
  Integer: "statics/images/sysml/PrimitiveType.svg",
  Real: "statics/images/sysml/PrimitiveType.svg",
  Boolean: "statics/images/sysml/PrimitiveType.svg",
  String: "statics/images/sysml/PrimitiveType.svg",
  Enumeration: "statics/images/sysml/Metaclass.svg"
};

const portSelectList = [
  {
    value: 0,
    label: "None"
  },
  {
    value: 1,
    label: "Flow Port"
  },
  {
    value: 2,
    label: "Proxy Port"
  }
];
const blockSelectList = ref<SelectOption[]>([]);
const currentName = ref("block");
const attachFile = ref(false);
const tableData = ref<FmuResolutionOptionItem[]>([]);
const changeOption = (row: FmuResolutionOptionItem, value: SelectOption) => {
  row.interfaceBlock = {
    icon: value.icon as string,
    name: value.label,
    id: value.value
  };
};
const handleAsPortOption = (row: FmuResolutionOptionItem, value: number) => {
  row.asPort = value;
  if (value !== 1) {
    row.interfaceBlock = {
      icon: "",
      name: "",
      id: ""
    };
  }
};
const handleSelectAll = () => {
  tableData.value.filter(one => {
    one.isCheck = true;
  });
};
const handleCancelSelectAll = () => {
  tableData.value.filter(one => {
    if (!one.disabled) {
      one.isCheck = false;
    }
  });
};
function handleCancel() {
  handleclose({ windowName: WindowName.FMUOptionWindow, success: false });
}
const handleSave = async () => {
  console.time("handle save");
  if (!currentName.value) return;
  if (!allData.value) return;
  const { guid, fmuVersion, modelIdentifier } = allData.value;
  loading.popup("正在保存...");
  const fileInfo = await localFile.readAttachedFileInfo(allData.value.filePath);
  const req = {
    projectId: query.projectId,
    modelName: allData.value.modelName,
    name: currentName.value,
    attachFile: attachFile.value,
    filePath: allData.value.filePath,
    data: tableData.value.filter(one => one.isCheck),
    guid,
    fmuVersion,
    modelIdentifier,
    fileInfo,
    parentId: query.parentId
  };
  if (query.isEdit == "true") {
    if (query.modelId) {
      await projectService
        .editFMUOption({
          projectId: query.projectId,
          fileInfo,
          name: currentName.value,
          data: tableData.value.filter(one => one.isCheck && !one.disabled),
          modelId: query.modelId,
          attachFile: attachFile.value,
          disAbaleAttachFile: !!allData.value.disAbaleAttachFile
        })
        .finally(() => {
          loading.close();
        });
    }
  } else {
    await projectService.saveFMUOption(req).finally(() => {
      loading.close();
    });
  }

  console.timeEnd("handle save");
  handleclose({ windowName: WindowName.FMUOptionWindow, success: false });
};
function handleclose(data: CloseData) {
  saveLoading.value = false;
  ipcWindowUtil.closeWindow(data);
}
const loadData = async () => {
  allData.value = JSON.parse(query.data) as FmuResolutionOptionData;
  tableData.value = allData.value.data;
  // 第一次导入的时候默认勾选
  if (query.isEdit == "false") {
    tableData.value.forEach(one => {
      if (["out", "in"].includes(one.direction)) {
        one.isCheck = true;
      }
    });
  }
  currentName.value = allData.value.modelName;
  blockSelectList.value = (await modelService.getInterFaceBlocks(query.projectId)).map(one => {
    return {
      label: one.name,
      value: one.id,
      icon: one.icon
    };
  });
  attachFile.value = !!allData.value.disAbaleAttachFile;
};

onMounted(async () => {
  await loadData();
});
</script>
<style lang="scss">
.v-fmu-option {
  // .fmu_content,
  // .fmu_top,
  // .fmu_footer,
  // .fmu_banner {
  //   // border: 1px solid;

  // }

  .fmu_top,
  .fmu_footer {
    height: 35px;
  }

  .requiredInput {
    .el-input__wrapper.is-focus {
      border: 1px red solid !important;
      box-shadow: none;
    }

    .el-input__wrapper {
      border: 1px red solid !important;
    }
  }

  .disabled {
    color: #cccccc;
  }

  .fmu_banner {
    // overflow-y: scroll;
    height: calc(100% - 70px);

    .cell {
      line-height: 24px;
      white-space: nowrap;
      display: flex;
      align-items: center;

      .el-table__placeholder {
        display: none;
        width: 16px;
      }

      .el-table__expand-icon {
        vertical-align: middle;
        transform: none;
        margin-right: 4px;

        &::before {
          content: "";
          width: 12px;
          height: 12px;
          display: block;
          background: url("/statics/icons/app/iconadd.svg") no-repeat;
          background-size: cover;
        }

        &.el-table__expand-icon--expanded {
          &::before {
            background: url("/statics/icons/table/iconspread2.svg") no-repeat;
            background-size: cover;
          }
        }

        .el-icon {
          display: none;
        }
      }

      .text {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        flex: 1;
      }
    }
  }

  .fmu_content {
    height: calc(100% - 100px);
    padding: 15px 15px 0px 15px;
  }

  .fmu_top {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    > span {
      margin-right: 15px;
    }

    .block_name {
      .el-input {
        width: 230px;
        font-weight: bold;
      }
    }

    .select_btn {
      color: #5f6c88;
      cursor: pointer;
    }
  }
}
</style>
